import React, { useState, useEffect } from 'react';
import {Card, Table, Pagination, Divider, ResponsiveGrid, Button, Box, Form, Input, Select, Icon, Radio, Upload, Loading,Dialog,Message, } from '@alifd/next';
import styles from './index.module.scss';
import {listPage, optionList, enable, disable, deleteUser, detail, update} from '@/api/UserAPI'
import {upLoadImage} from '@/api/CommonAPI'
import AddUser from '../AddUser/AddUser';
import  UpdateUser from '../UpdateUser/UpdateUser';
import  API_URL from '@/api/ApiUrl';
import {getCookieBBT, getBBTKey} from '@/utils/cookie'
const { Cell } = ResponsiveGrid;
const { Option } = Select;
const FormItem = Form.Item;
const userTypesData = [{code: "",name:"请选择"}];
const userStatesData = [{code:"",name:"请选择"}];
const sexesData = [{code:"",name:"请选择"}];
let optionFlag = true
const DEFAULT_DATA = {
  userTypes: userTypesData,
  userStates: userStatesData,
  sexes: sexesData,
  userList: [],
  tableColumn: {
    id: '标识',
    // serialNum: '序列号',
    name: '姓名',
    nickName: '昵称',
    loginName: '登录名',
    userTypeV: '类型',
    sexV: '性别',
    stateV: '状态',
    createTime: '创建时间'
  },
  // 查询参数
  QueryParam: {
    page:{
      current: 1,
      size: 10
    },
    query: "",
    state: null,
    userType: null,
    sex: null,
  },
  total: 0,
};
const formItemLayout = {
  colSpan: 6,
};

const DEFAULT_DATA_UPDATE = {
    id: '',
    userType: '0',
    sex: '1',
    loginName:'',
    password:'',
    phoneNum:'',
    name:'',
    code:'',
    nickName:'',
    logoUrl:'',
    logoUrlId:'',
  };
const TableList = props => {
  const { dataSource = DEFAULT_DATA } = props;
  const [loading, setLoading] = useState(true);
  const [expand, setExpand] = useState(false);
  const [sexValue, setSex] = useState(null);
  const [queryValue, setQuery] = useState("");
  const [userTypeValue, setUserTyp] = useState(null);
  const [stateTypeValue, setStateType] = useState(null);
  
  useEffect(() => {
    if(optionFlag){
      // 加载下拉框信息
      optionList().then((data)=>{
        if(data){
          data.userTypes.forEach(e => {
            userTypesData.push(e)
          });
          data.userStates.forEach(e => {
            userStatesData.push(e)
          });
          data.sexes.forEach(e => {
            sexesData.push(e)
          });
          optionFlag = false
        }else{
          Message.error('加载下拉列表信息失败')
        }

      });
    }

    if(loading){
      // 1.1 调用 UserAPI listPage 接口
      listPage(DEFAULT_DATA.QueryParam).then((data)=>{
        if(data){
          const list = data.records;
          DEFAULT_DATA.total = data.total;
          DEFAULT_DATA.userList = list;
          setLoading(false)
        }
      });
    }
  });

  const onFreshList = () => {
    // console.log("父组件刷新中...start")
    setLoading(true);
    // console.log("父组件刷新中...end")
  }
  const onOperation = () => {
    setLoading(true);
  };

  const onPaginationChange = (e) => {
    console.log("分页查询：", e)
    dataSource.QueryParam.page.current = e 
    setLoading(true);
  };

  const toggleSearchList = () => {
    setExpand(!expand);
  };

  const changeQuery = (e) => {
    setQuery(e)
    dataSource.QueryParam.query = e;
  };
  const changeUserState = (e) => {
    setStateType(e)
    dataSource.QueryParam.state = e;
  };

  const changeUserType = (e) => {
    setUserTyp(e)
    dataSource.QueryParam.userType = e;
  };
  const changeSex = (e) => {
    setSex(e);
    dataSource.QueryParam.sex = e;
  };
  // 重置
  const onReset = () => {
    dataSource.QueryParam.query = null
    dataSource.QueryParam.state = null
    dataSource.QueryParam.userType = null
    dataSource.QueryParam.sex = null
    setQuery(null)
    setUserTyp(null)
    setStateType(null)
    setSex(null)
  };

  // 启用
  const enableButton = (v) => {
    Dialog.confirm({
      title: '是否启用',
      onOk: () => {
        enable(v).then((flag)=>{
          if(flag){
            Message.success('启用成功')
            // 刷新列表数据
            setLoading(true);
          }
        })
      },
    })
  };
  // 禁用
  const disableButton = (v) => {
    Dialog.confirm({
      title: '是否禁用',
      onOk: () => {
        disable(v).then((flag)=>{
          if(flag){
            Message.success('禁用成功')
            // 刷新列表数据
            setLoading(true);
          }
        })
      },
    })
  };
  // 删除
  const delButton = (v) => {
    Dialog.confirm({
      title: '是否确定要删除',
      onOk: () => {
        deleteUser(v).then((flag)=>{
          if(flag){
            Message.success('删除成功')
            // 刷新列表数据
            setLoading(true);
          }
        })
      },
    })
  };

  /****************************************************修改部分 START ***************************** */

  // 修改表单部分
  const { dataSourceUpdate = DEFAULT_DATA_UPDATE} = props;
  const [postData, setPostData] = useState(dataSourceUpdate);
  // Dialog 弹框部分
  const [showState, setShowState] = useState(false);
  const [visible, setVisible] = useState(false);
  const [short, setShort] = useState(false);
  const [shouldUpdatePosition, setShouldUpdatePosition] = useState(true);
  const [sexUpdateValue, setUpdateSex] = useState(null);
  const [imageData, setImageData] = useState([]);
  
    // 1 打开弹框
    const openModifyComponent = (id) => {
        // 查询单条信息
        detail(id).then((data)=>{
          if(data){
            // 解析数据复制
            dataSourceUpdate.id = data.id,
            dataSourceUpdate.userType = String(data.userType),
            dataSourceUpdate.sex = String(data.sex),
            dataSourceUpdate.loginName = data.loginName,
            dataSourceUpdate.password = data.password,
            dataSourceUpdate.phoneNum = data.phoneNum,
            dataSourceUpdate.name = data.name,
            dataSourceUpdate.code = data.code,
            dataSourceUpdate.nickName = data.nickName,
            dataSourceUpdate.logoUrl = data.logoUrl,
            dataSourceUpdate.logoUrlId = data.logoUrlId,
            setImageData([])
            if(data.logoUrl){
              imageData.push({
                uid: data.logoUrlId,
                state: 'done',
                url: data.logoUrl,
              });
              setImageData(imageData)
            }
            setPostData(dataSourceUpdate)
            setVisible(true)
            setShort(true)
          }
        });
    };
    // 2 关闭弹框
    const onClose = () => {
      setImageData([])
      setVisible(false)
    };
    // 3 更新位置
    const toggleShouldUpdatePosition = () => {
        setShouldUpdatePosition(shouldUpdatePosition)
    };
    
    const DEFAULT_ON_SUBMIT = (values, errors) => {
      if (errors) {
        console.log('errors', errors);
        return;
      }
    
      console.log('values:', values);
      Message.success('提交成功');
    };

  const formChange = values => {
    setPostData(values);
  };
  const onCancel = () => {
      onClose();
  };
  // 上传附件
  const upLoadImageBegin = (info) => {
    // 调用上传API
    upLoadImage( 'file', info.file).then((data)=>{
      // console.log('上传成功返回数据*****', data)
      // 赋值URL和ID
      dataSourceUpdate.logoUrl = data.url
      dataSourceUpdate.logoUrlId = data.id
      // 回显信息
      let onSuccessInfo = {
        success: true,
        url: data.url,
        uid: data.id,
      }
      info.onSuccess(onSuccessInfo);
    });
  };

  // 提交表单信息
  const onSubmitUpdate = (values, errors) => {
      if (errors) {
        console.log('errors', errors);
        return;
      }
      // 处理上传文件属性
      delete values.file
      values.logoUrl= dataSourceUpdate.logoUrl;
      values.logoUrlId = dataSourceUpdate.logoUrlId
      // 调用新增用户API接口
      update(values).then((flag)=>{
          if(flag){
              Message.success('修改成功');
              setPostData({}); // 清空表单源数据
              setImageData([])
              onClose();
              setLoading(true);
          }
      });
  };
  /****************************************************修改部分--END ***************************** */
  return (
    <>
      <Card free>
        <Card.Content>
          <Box padding={10}>
            <Form responsive fullWidth labelAlign="top">
              <FormItem colSpan={2} label="模糊条件">
                <Input value={queryValue} onChange={changeQuery} placeholder="输入姓名、昵称、登录名、电话" />
              </FormItem>
              <FormItem colSpan={2} label="用户状态">
                <Select placeholder="选择状态" value={stateTypeValue} onChange={changeUserState} >
                {(
                    (dataSource.userStates || []).map((item, i) => {
                      return (
                        <Option key={i} value={item.code}>{item.name}</Option>
                      );
                    })
                )}
                </Select>
              </FormItem>
              <FormItem colSpan={2} label="用户类型">
                <Select placeholder="选择类型" value={userTypeValue}  onChange={changeUserType}>
                {(
                    (dataSource.userTypes || []).map((item, i) => {
                      return (
                        <Option key={i} value={item.code}>{item.name}</Option>
                      );
                    })
                )}
                </Select>
              </FormItem>
              <FormItem colSpan={2} label="性别">
                <Select value={sexValue} placeholder="选择性别" onChange={changeSex}>
                {(
                    (dataSource.sexes || []).map((item, i) => {
                      return (
                        <Option key={i} value={item.code}>{item.name}</Option>
                      );
                    })
                )}
                </Select>
              </FormItem>
              <Cell colSpan={3} className={styles.btns}>
                <Box spacing={8} direction="row" align="flex-end" justify="center" style={{height: '100%',}}>
                  <Button type="primary" onClick={onOperation}>查询</Button>
                  <Form.Reset onClick={onReset}>重置</Form.Reset>
                </Box>
              </Cell>
            </Form>
          </Box>
          <Divider dashed />
          <div className={styles.Main}>
            <Loading visible={loading}>
              <div className={styles.add}>
                <AddUser onFreshList = {onFreshList}/>
              </div>
              <Table
                hasBorder={false}
                className={styles.Table}
                dataSource={dataSource.userList}
                rowSelection={{
                  columnProps: () => ({
                    lock: 'left',
                  }),
                }}
              >
                {Object.keys(dataSource.tableColumn).map(col => (
                  <Table.Column title={dataSource.tableColumn[col]} dataIndex={col} key={col} />
                ))}
                <Table.Column
                  title="操作" key={'id'}
                  cell={(stateV, key) => {
                    let model = dataSource.userList[key]
                    if(model.stateV =='禁用'){
                      return (
                        <div className={styles.opt}>
                          <Button type="primary" text onClick={()=>openModifyComponent(model.id)}>编辑</Button>
                          <Button type="primary" text style={{color: 'green'}} onClick={()=> enableButton(model.id) }>启用</Button>
                          <Button type="primary" text style={{color: 'red'}} onClick={()=> delButton(model.id)}>删除</Button>
                        </div>
                      )
                    }else{
                      return (
                        <div className={styles.opt}>
                        <Button type="primary" text onClick={()=>openModifyComponent(model.id)}>编辑</Button>
                          <Button type="primary" text style={{color: 'black'}} onClick={()=> disableButton(model.id)}>禁用</Button>
                          <Button type="primary" text style={{color: 'red'}} onClick={()=> delButton(model.id)} >删除</Button>
                        </div>
                      )
                    }
                    }
                  }
                />
              </Table>
              <Box margin={[15, 0, 0, 0]} direction="row" align="center" justify="space-between">
                <div className={styles.total}>
                  每页<span>{dataSource.QueryParam.page.size}</span>条，共<span>{dataSource.total}</span>条
                </div>
                <Pagination pageSize={dataSource.QueryParam.page.size} total={dataSource.total} onChange={onPaginationChange} />
              </Box>
            </Loading>
          </div>
        </Card.Content>
      </Card>
      
      <div> 
            <Dialog title="修改用户信息" visible={visible} footer ={false} onClose={onCancel}>
                <Card free className={styles.TwoColumnForm}>
                <Card.Content>

                    <Form responsive fullWidth value={postData} labelAlign="top" onChange={formChange}>
                        <FormItem {...formItemLayout} label="ID" required requiredMessage="必填" hidden>
                                <Input name="id" disabled/>
                        </FormItem>
                        <FormItem {...formItemLayout} label="账户登录名：" required requiredMessage="必填">
                            <Input placeholder="请输入用户登录名" name="loginName" />
                        </FormItem>
                        <FormItem {...formItemLayout} label="用户类型：">
                            <Radio.Group name="userType" aria-labelledby="用户类型~">
                                <Radio id="ordinary" value="0">普通用户</Radio>
                                <Radio id="manger" value="1">管理用户</Radio>
                                <Radio id="system" value="-1">系统用户</Radio>
                            </Radio.Group>
                        </FormItem>
                        <FormItem {...formItemLayout} label="账户密码：" required requiredMessage="必填">
                            <Input value="*******" name="password" disabled/>
                        </FormItem>

                        <FormItem {...formItemLayout} label="用户手机号：" required requiredMessage="必填">
                            <Input placeholder="请输入用户手机号" name="phoneNum" />
                        </FormItem>

                        <FormItem {...formItemLayout} label="用户姓名：" required requiredMessage="必填">
                            <Input placeholder="请输入用户姓名" name="name" />
                        </FormItem>
                        <FormItem {...formItemLayout} label="用户代码：" required requiredMessage="必填">
                            <Input placeholder="请输入用户代码" name="code" />
                        </FormItem>
                        <FormItem {...formItemLayout} label="用户昵称：" required requiredMessage="必填">
                            <Input placeholder="请输入用户昵称" name="nickName" />
                        </FormItem>
                        <FormItem {...formItemLayout} label="用户性别：" required requiredMessage="必填">
                            <Radio.Group name="sex" aria-labelledby="用户性别~">
                                <Radio id="man" value='1'>男</Radio>
                                <Radio id="woman" value='2'>女</Radio>
                            </Radio.Group>
                        </FormItem>

                        <FormItem {...formItemLayout} label="上传用户头像：" >
                            <Upload listType="image"
                            accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp" shape="card" 
                            name="file" 
                            limit={1}
                            request={upLoadImageBegin} 
                            defaultValue={imageData}
                            >
                            </Upload>
                        </FormItem>

                        <FormItem colSpan={12} style={{marginLeft:'35%'}}>
                            <Box spacing={8} direction="row" align="center">
                                <Form.Submit type="primary" onClick={onSubmitUpdate} validate>提交</Form.Submit>
                                <Button onClick={onCancel} type="secondary">取消</Button>
                            </Box>
                        </FormItem>
                    </Form>
                </Card.Content>
                </Card>
            </Dialog>
        </div>
    </>
  );
};

export default TableList;
